import {databus} from '../databus'
let mjl = require('../../images/resource/map/mjl.js')
const screenWidth = window.innerWidth
const screenHeight = window.innerHeight
// 可以行走的瓷砖 垂直浮桥左右[192,352],[160,352], 左右浮桥[224,352],[224,320],两格垂直楼梯[0,112],[32,112]
const roads = [
  [],
  // outside.png
  [[32,16],[48,64],[176,352],[192,240],[176,256],[224,336]],
  // room.png
  [[160,208],[160,192],[48,288],[0,304],[0,288],[48,304],[32,304],[32,288],[32,304],[16,304],[16,288],[32,112],[32,128],[16,128],[0,128],[0,112],[16,112],[32,96],[0,96],[16,96]],
  // maze.png
  [[0,112],[32,112],[64,80],[16,80],[64,32],[0,144],[0,176]]
]
// 行走图切换
const keyMap = {
  'up': 0,
  'down': 64,
  'left': 96,
  'right': 32
};
let lastKey = 'up'
// 行走偏移
const keyOffset = {
  'up': { ty: -1 },
  'down': { ty: 1 },
  'left': { tx: -1 },
  'right': { tx: 1 },
  'enter' : {},
  'esc' : {},
  'pup' : {},
  'pdown' : {}
};


export default class Player{
  constructor() {

    // 玩家默认处于屏幕底部居中位置
    this.x = screenWidth / 2 - this.width / 2
    this.y = screenHeight - this.height - 30

    this.touched = false

    this.bullets = []

    // 初始化事件监听
    this.initEvent()
  }

  /**
   * 当手指触摸屏幕的时候
   * 判断是否按在按键上
   * @param {Number} x: 手指的X轴坐标
   * @param {Number} y: 手指的Y轴坐标
   */
  checkIsFingerOnKey(x, y, key) {
    let isFingerOn = false
    const btnL  = databus.controllSprites[0]
    const btnR  = databus.controllSprites[1]
    
    if(key=='up'){
      isFingerOn = !!(x >= (btnL.tx+btnL.twidth/3) 
      && y >= (btnL.ty)  
      && x <= (btnL.tx+btnL.twidth/3*2) 
      && y <= (btnL.ty+btnL.theight/3)  )
    }else if(key=='down'){
      isFingerOn = !!(x >= (btnL.tx+btnL.twidth/3) 
      && y >= (btnL.ty+btnL.theight/3*2)  
      && x <= (btnL.tx+btnL.twidth/3*2) 
      && y <= (btnL.ty+btnL.theight/3*3)  )
    }else if(key=='left'){
      isFingerOn = !!(x >= (btnL.tx) 
      && y >= (btnL.ty+btnL.theight/3)  
      && x <= (btnL.tx+btnL.twidth/3) 
      && y <= (btnL.ty+btnL.theight/3*2)  )
    }else if(key=='right'){
      isFingerOn = !!(x >= (btnL.tx+btnL.twidth/3*2) 
      && y >= (btnL.ty+btnL.theight/3)  
      && x <= (btnL.tx+btnL.twidth/3*3) 
      && y <= (btnL.ty+btnL.theight/3*2)  )
    }else if(key=='pup'){
      isFingerOn = !!(x >= (btnR.tx+btnR.twidth/3) 
      && y >= (btnR.ty)  
      && x <= (btnR.tx+btnR.twidth/3*2) 
      && y <= (btnR.ty+btnR.theight/3)  )
    }else if(key=='esc'){
      isFingerOn = !!(x >= (btnR.tx+btnR.twidth/3) 
      && y >= (btnR.ty+btnR.theight/3*2)  
      && x <= (btnR.tx+btnR.twidth/3*2) 
      && y <= (btnR.ty+btnR.theight/3*3)  )
    }else if(key=='pdown'){
      isFingerOn = !!(x >= (btnR.tx) 
      && y >= (btnR.ty+btnR.theight/3)  
      && x <= (btnR.tx+btnR.twidth/3) 
      && y <= (btnR.ty+btnR.theight/3*2)  )
    }else if(key=='enter'){
      isFingerOn = !!(x >= (btnR.tx+btnR.twidth/3*2) 
      && y >= (btnR.ty+btnR.theight/3)  
      && x <= (btnR.tx+btnR.twidth/3*3) 
      && y <= (btnR.ty+btnR.theight/3*2)  )
    }
    return isFingerOn
  }

  

  /**
   * 玩家响应手指的触摸事件
   * 改变战机的位置
   */
  initEvent() {
    canvas.addEventListener('touchstart', ((e) => {
      e.preventDefault()
      
      const x = e.touches[0].clientX
      const y = e.touches[0].clientY
      
      //
      if (this.checkIsFingerOnKey(x, y, 'up')) {
        this.touched = true
        this.frameKeyPress('up')
        // console.log('touchstart-up')
        
      }
      if (this.checkIsFingerOnKey(x, y, 'down')) {
        this.touched = true
        this.frameKeyPress('down')
        // console.log('touchstart-down')
        
      }
      if (this.checkIsFingerOnKey(x, y, 'left')) {
        this.touched = true
        this.frameKeyPress('left')
        // console.log('touchstart-left')
        
      }
      if (this.checkIsFingerOnKey(x, y, 'right')) {
        this.touched = true
        this.frameKeyPress('right')
        // console.log('touchstart-right')
        
      }
      if (this.checkIsFingerOnKey(x, y, 'enter')) {
        this.touched = true
        this.frameKeyPress('enter')
        // console.log('touchstart-enter')
        
      }
      if (this.checkIsFingerOnKey(x, y, 'esc')) {
        this.touched = true
        this.frameKeyPress('esc')
        // console.log('touchstart-esc')
        
      }
      if (this.checkIsFingerOnKey(x, y, 'pup')) {
        this.touched = true
        this.frameKeyPress('pup')
        // console.log('touchstart-pup')
        
      }
      if (this.checkIsFingerOnKey(x, y, 'pdown')) {
        this.touched = true
        this.frameKeyPress('pdown')
        // console.log('touchstart-pdown')
        
      }
    }))

    canvas.addEventListener('touchmove', ((e) => {
      e.preventDefault()

      const x = e.touches[0].clientX
      const y = e.touches[0].clientY
      // if (this.touched) this.setAirPosAcrossFingerPosZ(x, y)
    }))

    canvas.addEventListener('touchend', ((e) => {
      e.preventDefault()

      this.touched = false
    }))
  }

  /**
   * 界面按下按钮
   */
  async frameKeyPress(key) {
    // 开始界面
    // console.log(databus)
    if(databus.mode=='startMovie'){
      databus.mode = 'start'
    } else if(databus.mode === 'start'){
      databus.svSprites[1].ty = key === 'up' ? 3*16*devicePixelRatio : key === 'down' ? 4.5*16*devicePixelRatio : databus.svSprites[1].ty
      if(key === 'enter'&& databus.svSprites[1].ty===3*16*devicePixelRatio){
        databus.mode='world'
        
        const found = databus.mapConverts.some(item => item===databus.worldMap.spriteName);
        await databus.worldMap.readResource(!found)
        // console.log(databus.worldMap.map.event_layer)
        if(!found)databus.mapConverts.push(databus.worldMap.spriteName)
        
        // 进入游戏执行地图脚本
        databus.worldMap.runMapScript()
      }
      
    }else if(databus.mode === 'world'){
      
      
      // mjl.mjl_runScript('map/sqg_bai_cao_di/enter_sqg.js')
      
      let sayMessages = databus.msgBox.filter(msg => msg.msgType === 'sayMsg');
      
      if(!databus.gameStatus['fu_mo_ji_mission_start']||sayMessages.length>0||databus.movies.length>0){
        databus.msgBox=sayMessages.slice(1);
        // console.log(databus.msgBox);  // 输出一个包含所有满足条件的对象的数组
      }else{
 
        if (keyOffset[key]) {
          
          let nextPos = {x: (databus.hero.tx || 0) + (keyOffset[key].tx || 0)+8,y:(databus.hero.ty || 0) + (keyOffset[key].ty || 0)+4}
          let tile,tileset_id;
          // 当地板瓷砖只有一层
          if(databus.worldMap.map.tile_layer.tiles){
            tile = databus.worldMap.map.tile_layer.tiles.find(tile => tile.i[0] === nextPos.x && tile.i[1]=== nextPos.y);
            tileset_id = databus.worldMap.map.tile_layer.tileset_id
            
          }else{
            // 地板瓷砖有多层
            if(!tile){
              for(let j=0;j<databus.worldMap.map.tile_layer.length;j++){
                tile = databus.worldMap.map.tile_layer[j].tiles.find(tile => tile.i[0] === nextPos.x && tile.i[1]=== nextPos.y);
                tileset_id = databus.worldMap.map.tile_layer[j].tileset_id
                if (tile) break;
              }
            }
            
          }
  
          const eventTile = databus.worldMap.map.event_layer.tiles.find(tile => tile.i[0] === nextPos.x && tile.i[1]=== nextPos.y);
          
          const objTile = Object.keys(databus.worldMap.map.obj_layer.obj).length === 0 ? undefined : findObject(databus.worldMap.map.obj_layer.obj, nextPos);
          let nextPosNpc =  {x: (databus.hero.tx || 0) + (keyOffset[lastKey].tx || 0)+8,y:(databus.hero.ty || 0) + (keyOffset[lastKey].ty || 0)+4}
          let npc = databus.npcs.find(npc => (npc[0].tx === nextPos.x&&npc[0].ty === nextPos.y||npc[0].tx === nextPos.x&&npc[0].ty+1 === nextPos.y))
          npc = npc == undefined ? databus.npcs.find(npc => (npc[0].tx === nextPosNpc.x&&npc[0].ty === nextPosNpc.y||npc[0].tx === nextPosNpc.x&&npc[0].ty+1 === nextPosNpc.y)):npc
          // const npcEventTile = npc == undefined ?{}:databus.worldMap.map.event_layer.tiles.find(tile => tile.i[0] === npc.tx && tile.i[1]=== npc.ty);
          // console.log(eventTile,nextPos,npc,npcEventTile)
          // 根据瓷砖图tileset的不同来设置是否能行走
          // console.log(tileset_id)
          let flag = (tile && tile.i && tile.i.length >= 4) && roads[tileset_id].some(road => road[0] === tile.i[2] && road[1] === tile.i[3]);
          // 先判断是否是对象瓷砖
          if(key == 'up'||key == 'down'||key == 'left'||key == 'right'){
            databus.hero.x = (databus.hero.x === 32) ? 0 : databus.hero.x + 16;
            databus.hero.y = (keyMap[key] === undefined) ? 64 : keyMap[key];
          }
          if(!objTile){
            // 如果是npc 回车后调用npc脚本
            
            if(npc){
              if(key == 'enter'){
                console.log(npc)
                if(npc[1]){
                  mjl.mjl_runScript(npc[1])
                }  
              }

            }else{
              // 在判断是否为空白瓷砖或者可行走瓷砖
              
              if(!tile||flag){
                databus.hero.tx = (databus.hero.tx || 0) + (keyOffset[key].tx || 0);
                databus.hero.ty = (databus.hero.ty || 0) + (keyOffset[key].ty || 0);
                databus.hero.posx = databus.hero.tx+8
                databus.hero.posy = databus.hero.ty+4
              }
            }
          }
          
          const eventJs = eventTile && eventTile.i && eventTile.i.length > 2 ? eventTile.i[3] : undefined;
       
          // console.log(databus.hero.tx,databus.hero.ty,tile,databus.npcs)
          if(eventJs){
            mjl.mjl_runScript(eventJs)
          }  
          lastKey = ['up', 'down', 'left', 'right'].includes(key) ? key : lastKey;

          
        }
      }
      
    }
    // 对象碰撞测试
    function findObject(objArray, nextPos) {
      
      for (let i = 0; i < objArray.length; i++) {
        const obj = objArray[i];
        let posDeviation = obj.posDeviation === undefined ? [0,0]:obj.posDeviation
        let posArea = obj.posArea === undefined ? [0,0]:obj.posArea
        // console.log(nextPos,obj, posDeviation,posArea,(obj.pos[0] + posDeviation[0]),(obj.pos[1] + posDeviation[1]),(obj.pos[0] + posDeviation[0] + posArea[0]),(obj.pos[1] +posDeviation[1] + posArea[1]))
        if (nextPos.x >= (obj.pos[0] + posDeviation[0]) &&
            nextPos.y >= (obj.pos[1] + posDeviation[1]) &&
            nextPos.x <= (obj.pos[0] + posDeviation[0] + posArea[0]-1) &&
            nextPos.y <= (obj.pos[1] +posDeviation[1] + posArea[1]-1)) {
              // console.log(objArray, nextPos,obj)
          return obj;
        }
      }
      return null;
    }
  }
  

}
